# -*- coding: utf-8 -*-
# 角色相关模型

import os
import time
import traceback
from django.db import models
from .resource import Resource
from public_util.util.base import (BaseModelMixin,
                                   CacheAttribute,
                                   CachedClassAttribute)


class RoleManagerMixin(object):

    def add_resource_member(self, name, id):
        '''增加资源对象
        @name  资源名
        @id    资源对象id
        '''
        resource_objs = self.resource.all().filter(name=name)
        if resource_objs:
            resource_objs[0].add_member(id)
            resource_objs[0].save()

    def get_resource(self, name):
        resource_ids = self.resource.get(name=name).members
        return Resource.resource_map[name].objects.filter(id__in=resource_ids).distinct()

    def get_resource_channel_id(self, name):
        # 获取当前角色所有的渠道id
        resource_ids = self.resource.get(name=name).members
        return resource_ids

    def create_resource(self, name, id_list):
        '''角色创建资源
        @资源名
        @id列表
        '''
        if not self.id:  # 新建时没有对象,先保存一下
            self.save()
        resource, created = Resource.objects.get_or_create(name=name, role_id=self.id)
        resource.members = id_list
        resource.save()
        self.resource.add(resource)


def error_Log(msg):
    # # 日志
    path = os.getcwd()
    path = path + '/role_save.txt'
    check_dir = os.path.dirname(path)
    isExists = os.path.exists(check_dir)
    now_time = time.strftime("%Y-%m-%d %H:%M:%S")
    if not isExists:
        os.makedirs(check_dir)
    with open(path, 'a') as f:
        f.write('time:%s --->INFO:%s ' % (now_time, msg) + '\n')


class Role(models.Model, BaseModelMixin, RoleManagerMixin):
    """角色模型"""

    class RoleType:
        ADMIN = 0  # 管理员
        NORMAL = 1  # 普通账号

    TYPE_CHOICES = ((RoleType.NORMAL, '普通'), (RoleType.ADMIN, '管理员'))

    name = models.CharField('角色名', max_length=50, unique=True, db_index=True)
    parent_name = models.CharField('主管名', max_length=50, default='', db_index=True)
    type = models.SmallIntegerField('角色类型', default=1, choices=TYPE_CHOICES)
    remark = models.CharField('角色描述', default='', max_length=100)

    resource = models.ManyToManyField(Resource, verbose_name='资源对象')

    @CacheAttribute
    def resource_ids(self):
        _r = {}
        for r in self.resource.all():
            _r[r.name] = r.members
        return _r

    @property
    def is_manager(self):
        return self.type == self.RoleType.ADMIN

    def save(self, *args, **kwargs):
        msg = repr(traceback.format_stack())
        error_Log(msg)
        super(Role, self).save(*args, **kwargs)
        # 更新角色缓存
        # from center.tasks import load_role_server_cache
        # from package.models import Admin
        # try:
        #     load_role_server_cache.delay([self])
        #     # 更新多角色缓存
        #     role_ids_key_list = []
        #     all_admin = Admin.objects.all()
        #     for admin_obj in all_admin:
        #         roles = admin_obj.get_roles()
        #         if len(roles) > 1:
        #             if self in roles:
        #                 role_ids_key = '_'.join(sorted([str(role.id) for role in roles]))
        #                 if role_ids_key not in role_ids_key_list:  # 只提取一个拥有该角色的用户
        #                     load_role_server_cache.delay(roles)
        #                     role_ids_key_list.append(role_ids_key)
        # except Exception as e:
        #     print(e)

    def delete(self, *args, **kwargs):
        for r in self.resource.all():
            r.delete()
        self.resource.clear()
        # role_id = str(self.id)
        super(Role, self).delete(*args, **kwargs)
        # 删除角色后删除缓存以及删除含有该角色的缓存
        # from public_util.util.cache import del_role_cache
        # from package.models import Admin
        # from django.core.cache import cache
        # cache_role_keys = cache.get('cache_role_key', set())
        # for role_key in cache_role_keys:
        #     roles_id = role_key.split('_')
        #     if role_id in roles_id:
        #         del_role_cache(role_key)

    def __unicode__(self):
        return '%s' % self.name

    class Meta:
        db_table = u'role'


Resource.register('role', Role)

